package com.nulldev.util.web.HttpServer3.util;

import java.io.IOException;
import java.io.InputStream;

import com.nulldev.util.data.Variables;
import com.nulldev.util.io.IOUtils;

public class SectionedInputStream extends InputStream {

	private final InputStream stream;
	private final int size;

	private boolean allowRepeating;
	private byte[] buffer = null;
	private int idx = -1;

	public SectionedInputStream(final InputStream is, final int size) {
		this(is, size, true);
	}

	public SectionedInputStream(final InputStream is, final int size, final boolean allowRepeating) {
		Variables.checkArgument(size > 0);
		this.stream = Variables.requireNonNullObject(is, "is");
		this.allowRepeating = allowRepeating;
		this.size = size;
	}

	@Override
	public int read() throws IOException {
		if (this.buffer == null) {
			this.buffer = new byte[this.size];
			IOUtils.readFully(this.stream, this.buffer);
		}
		if (this.idx + 1 >= this.size) {
			if (this.allowRepeating) {
				this.idx = -1;
			} else {
				return -1;
			}
		}
		this.idx += 1;
		return this.buffer[this.idx];
	}

	@Override
	public void close() throws IOException {
		this.idx = -1;
		this.allowRepeating = false;
	}

	@Override
	public int available() throws IOException {
		if (this.idx == -1) {
			return this.size;
		} else {
			return this.size - this.idx;
		}
	}

	@Override
	public long skip(final long n) throws IOException {
		if (!this.allowRepeating) {
			return 0;
		} else if (n > this.size) {
			return 0;
		} else if (this.idx + n >= this.size) {
			return 0;
		} else {
			this.idx += n;
			return n;
		}
	}
}
